package com.ecommerce.product.service.impl;

import com.ecommerce.product.dto.ProductCreateRequest;
import com.ecommerce.product.dto.ProductMapper;
import com.ecommerce.product.dto.ProductPageResponse;
import com.ecommerce.product.dto.ProductResponse;
import com.ecommerce.product.dto.ProductUpdateRequest;
import com.ecommerce.product.entity.Product;
import com.ecommerce.product.repository.ProductRepository;
import com.ecommerce.product.service.ProductService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 产品服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductServiceImpl implements ProductService {

    private final ProductRepository productRepository;
    private final ProductMapper productMapper;

    @Override
    @Transactional
    public ProductResponse createProduct(ProductCreateRequest createRequest) {
        log.info("创建产品: {}", createRequest.getName());
        
        Product product = productMapper.createRequestToEntity(createRequest);
        product = productRepository.save(product);
        
        log.info("产品创建成功, ID: {}", product.getId());
        return productMapper.entityToResponseDto(product);
    }

    @Override
    @Transactional
    public ProductResponse updateProduct(Long productId, ProductUpdateRequest updateRequest) {
        log.info("更新产品, ID: {}", productId);
        
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("产品不存在: " + productId));
        
        productMapper.updateEntity(product, updateRequest);
        product = productRepository.save(product);
        
        log.info("产品更新成功, ID: {}", productId);
        return productMapper.entityToResponseDto(product);
    }

    @Override
    public ProductResponse getProductById(Long productId) {
        log.info("获取产品详情, ID: {}", productId);
        
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("产品不存在: " + productId));
        
        return productMapper.entityToResponseDto(product);
    }

    @Override
    public ProductPageResponse getProducts(Integer page, Integer size) {
        log.info("分页获取产品列表, 页码: {}, 每页大小: {}", page, size);
        
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Product> productPage = productRepository.findAll(pageable);
        
        List<ProductResponse> products = productPage.getContent().stream()
                .map(productMapper::entityToResponseDto)
                .collect(Collectors.toList());
        
        ProductPageResponse response = new ProductPageResponse();
        response.setProducts(products);
        response.setTotal(productPage.getTotalElements());
        response.setPage(page);
        response.setSize(size);
        response.setTotalPages(productPage.getTotalPages());
        
        return response;
    }

    @Override
    @Transactional
    public void deleteProduct(Long productId) {
        log.info("删除产品, ID: {}", productId);
        
        if (!productRepository.existsById(productId)) {
            throw new RuntimeException("产品不存在: " + productId);
        }
        
        productRepository.deleteById(productId);
        log.info("产品删除成功, ID: {}", productId);
    }

    @Override
    @Transactional
    public void reduceStock(Long productId, Integer quantity) {
        log.info("减少产品库存, 产品ID: {}, 数量: {}", productId, quantity);
        
        if (quantity <= 0) {
            throw new RuntimeException("减少库存数量必须大于0");
        }
        
        int affectedRows = productRepository.reduceStock(productId, quantity);
        if (affectedRows == 0) {
            throw new RuntimeException("库存不足或产品不存在");
        }
        
        log.info("产品库存减少成功, 产品ID: {}, 数量: {}", productId, quantity);
    }

    @Override
    public List<ProductResponse> getHotProducts(Integer limit) {
        log.info("获取热门商品, 限制数量: {}", limit);
        
        // 这里实现获取热门商品的逻辑
        // 可以根据销量、评分等条件来筛选热门商品
        Pageable pageable = PageRequest.of(0, limit);
        List<Product> hotProducts = productRepository.findTopNByOrderBySalesDesc(pageable);
        
        return hotProducts.stream()
                .map(productMapper::entityToResponseDto)
                .collect(Collectors.toList());
    }

    @Override
    public ProductPageResponse searchProducts(String keyword, Integer page, Integer size) {
        log.info("搜索产品, 关键词: {}, 页码: {}, 每页大小: {}", keyword, page, size);
        
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<Product> productPage;
        
        if (keyword == null || keyword.trim().isEmpty()) {
            // 如果关键词为空，则返回所有产品
            productPage = productRepository.findAll(pageable);
        } else {
            // 根据关键词搜索产品
            productPage = productRepository.findByNameOrDescriptionContainingIgnoreCase(keyword, pageable);
        }
        
        List<ProductResponse> products = productPage.getContent().stream()
                .map(productMapper::entityToResponseDto)
                .collect(Collectors.toList());
        
        ProductPageResponse response = new ProductPageResponse();
        response.setProducts(products);
        response.setTotal(productPage.getTotalElements());
        response.setPage(page);
        response.setSize(size);
        response.setTotalPages(productPage.getTotalPages());
        
        return response;
    }
}